#include "key_proc.h"
#include "pin_map.h"
#include "driver/gpio.h"
#include "esp_log.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/queue.h"

#define TAG "KEY_PROC"

static QueueHandle_t key_queue = NULL;
static BaseType_t key_task_id = 0;

static void IRAM_ATTR gpio_isr_handler(void* arg)
{
    uint32_t gpio_num = (uint32_t) arg;
    uint32_t key_level = gpio_get_level((gpio_num_t)gpio_num);
    BaseType_t pxHigherPriorityTaskWoken = pdFALSE;
    // 判断按键状态是否为低电平
    if(key_level == 0) {
        xQueueSendFromISR(key_queue, &gpio_num, &pxHigherPriorityTaskWoken);
    }
}

static void key_task(void* arg)
{
    uint32_t gpio_num;
    while(1) {
        if(xQueueReceive(key_queue, &gpio_num, portMAX_DELAY)) {
            ESP_LOGI("KEY_TASK", "Key pressed on GPIO %ld", gpio_num);
            // 这里可以添加按键处理逻辑
        }
    }
}


void key_init(void)
{
    gpio_config_t input_key;

    input_key.pin_bit_mask = BIT64(PIN_BOOT_BUTTON);
    input_key.mode = GPIO_MODE_INPUT;
    input_key.pull_up_en = GPIO_PULLUP_ENABLE;
    input_key.pull_down_en = GPIO_PULLDOWN_DISABLE;
    input_key.intr_type = GPIO_INTR_NEGEDGE;
    gpio_config(&input_key);

    gpio_install_isr_service(5);

    gpio_isr_handler_add(PIN_BOOT_BUTTON, gpio_isr_handler, (void*) PIN_BOOT_BUTTON);

    key_queue = xQueueCreate(10, sizeof(uint32_t));

    key_task_id = xTaskCreate(key_task, "key_task", 2048, NULL, 10, NULL);
}